package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.UrlBase64;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
/**
 * 小米官方接口
 * **/
@Slf4j
public class Plugin_ECARD_P006 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }
    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){
        try {

            String SUPProductId = String.valueOf(data.get("SUPProductId"));
            String[] sls = SUPProductId.split(",");
            String product = sls[0];
            String card = sls[1];
            String channelId = sls[2];
            String AccountVal=String.valueOf(data.get("AccountVal"));
            String ChannelOrderCode=String.valueOf(data.get("ChannelOrderCode"));

            Map<String,String> dataParams = new LinkedHashMap<>();
            dataParams.put("phone",AccountVal);
            dataParams.put("source_id",apiConfig.getString("USERID"));
            dataParams.put("channel_id",channelId);
            dataParams.put("product",product);
            dataParams.put("card",card);
            dataParams.put("ts",String.valueOf(Math.toIntExact(System.currentTimeMillis() / 1000)));
            dataParams.put("order_id",ChannelOrderCode);
            String signStr=getSignStr(dataParams);
            String signature=getSignByPrivateKey(signStr,apiConfig.getString("SecretKey"));
            dataParams.put("signature",signature);




            String url=apiConfig.getString("SubmitURL");
            String responseContent = HttpTool.HttpPost(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code=retobj.getString("status");
            String msg=retobj.getString("status_msg");

            if("0".equals(code)){
                return ChannelResult.success("充值成功");
            }else if ("1001".equals(code) || "1900".equals(code)){
                return ChannelResult.error(msg);
            }else {
                return ChannelResult.FAILED("错误码："+code+","+msg);
            }
        } catch (Exception ex) {
            log.error("小米提单接口出错:", ex);
            return ChannelResult.error("小米提单接口出错");
        }

    }
    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data){
        return  ChannelResult.error("无查询接口");

    }

    public  ChannelResult Notify(JSONObject apiConfig,Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }

    public static String getSignByPrivateKey(String str,String key) {
        try{
            byte[] keyBytes;  keyBytes = (new BASE64Decoder()).decodeBuffer(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            Signature sign = Signature.getInstance("SHA1withRSA");
            sign.initSign(privateKey);
            byte[] bysData = str.getBytes("UTF-8");
            sign.update(bysData);
            byte[] signByte = sign.sign();
            String signStr = new String(UrlBase64.encode(signByte), "utf-8");
            return  signStr;
        }catch (Exception ex){
            log.error("小米获取签名出错：", ex);
            return null;
        }
    }

    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null && item.getKey() != "") {
                    String key = String.valueOf(item.getKey());
                    String val = String.valueOf(item.getValue());
                    if(sb.length()>0){
                        sb.append("&");
                    }
                    if (StringUtils.hasLength(val)) {
                        sb.append(key +"="+ val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }
}
